import PageLayout from "@/components/PageLayout";
import {
  Button,
  Center,
  Flex,
  Pagination,
  Table,
  Text,
  TextInput,
} from "@mantine/core";
import dayjs from "dayjs";

import { useAPIUtils } from "@/components/APIUtilsProvider";
import { usePageTabManagementContext } from "@/components/PageTabManagementProvider";
import UserPill from "@/components/UserPill";
import { useTabbyData } from "@/hooks/useTabbyData";
import { useLocation } from "react-router-dom";

export default function NotificationList() {
  const { pathname } = useLocation();
  const { openPageTab } = usePageTabManagementContext();

  const [input, setInput] = useTabbyData(pathname, "keyword", {
    value: "",
  });
  const [pagingCondition, setPagingCondition] = useTabbyData(
    pathname,
    "pagingConditon",
    {
      keyword: "",
      pageIndex: 0,
      pageSize: 10,
    }
  );

  const { restGET, tanstackQuery, tanstackInvalidate, restPOST, restDELETE } =
    useAPIUtils();

  const search = () => {
    setPagingCondition({
      ...pagingCondition,
      pageIndex: 0,
      keyword: input.value,
    });
  };

  const deleteNotification = async (id) => {
    await restDELETE(`/notifications/${id}`);
    tanstackInvalidate("/notifications/mine");
  };
  const markNotificationAsRead = async (id) => {
    await restPOST(`/notifications/${id}/reading`);
    tanstackInvalidate("/notifications/mine");
  };

  const openNotification = async (id) => {
    await markNotificationAsRead(id);
    openPageTab(`/notifications/${id}`, "通知详情");
  };

  const notificationQuery = tanstackQuery(
    "/notifications/mine",
    {
      keyword: pagingCondition.keyword,
      page: pagingCondition.pageIndex,
      pageSize: pagingCondition.pageSize,
    },
    30 * 1000
  );

  const totalPages = notificationQuery.data?.totalPages;
  const rows = notificationQuery.data?.content.map((notification, index) => (
    <Table.Tr c={notification.read ? "dimmed" : ""} key={index}>
      <Table.Td>
        <Text>{notification.title}</Text>
      </Table.Td>
      <Table.Td>
        <UserPill username={notification.from} />
      </Table.Td>
      <Table.Td>{dayjs(notification.createdAt).fromNow()}</Table.Td>
      <Table.Td>
        <Button.Group>
          <Button
            variant="subtle"
            size="xs"
            onClick={() => deleteNotification(notification.id)}
          >
            删除
          </Button>
          <Button
            variant="subtle"
            disabled={notification.read}
            size="xs"
            onClick={() => markNotificationAsRead(notification.id)}
          >
            忽略
          </Button>
          <Button
            variant="subtle"
            size="xs"
            onClick={() => openNotification(notification.id)}
          >
            查看
          </Button>
        </Button.Group>
      </Table.Td>
    </Table.Tr>
  ));

  return (
    <PageLayout title={"通知 Notifications"}>
      <Flex
        mih={50}
        mb={20}
        gap="sm"
        justify="flex-end"
        align="center"
        direction="row"
        wrap="wrap"
      >
        <TextInput
          placeholder="请输入关键字"
          value={input?.value}
          onChange={(e) => {
            setInput((prev) => {
              prev.value = e.target.value;
            });
          }}
        />
        <Button onClick={search}>搜索</Button>
      </Flex>
      <Table verticalSpacing={"sm"}>
        <Table.Thead>
          <Table.Tr>
            <Table.Th w={"60%"}>标题</Table.Th>
            <Table.Th w={"10%"}>发信人</Table.Th>
            <Table.Th w={"15%"}>时间</Table.Th>
            <Table.Th>操作</Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>{rows}</Table.Tbody>
      </Table>
      <Center mt={40}>
        <Pagination
          total={totalPages}
          value={pagingCondition.pageIndex + 1}
          onChange={(e) => {
            setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
          }}
        />
      </Center>
    </PageLayout>
  );
}
